<script setup lang="ts">
import {onMounted, ref} from "vue";
import {Admin} from "../../interfaces/Admin.ts";
import {Result} from "../../interfaces/Result.ts";
import {adminLogin} from "../../apis/AdminApi.js";
import {elPrompt} from "../../utils/elPrompt.ts";
import router from "../../router/router.js";
import getLocalStorage from "../../utils/getLocalStorage.js";

const admin = ref<Admin>({
  password: "",
  email: "",
  username: ""
})

function login() {
  adminLogin(admin.value.username, admin.value.password, (result:Result<string>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    elPrompt("登录成功！", "success")
    const token = result.data
    localStorage.setItem('token', token)
    router.push('/admin')
  })
}

function toRegister() {
  router.push('/admin/register')
}

onMounted(() => {
  logout()
})

function logout() {
  const token = getLocalStorage('token', true)
  if (!token) return
  elPrompt('已退出当前用户！', "success")
  localStorage.clear()
}
</script>

<template>
<div class="admin">
  <div class="login-box">
    <h2>管理员登录</h2>
    <div class="form">
      <el-form>
        <el-form-item label="管理员用户名" prop="username">
          <el-input v-model="admin.username" type="text"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="admin.password" type="password" show-password/>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="login">登录</el-button>
      <el-button type="warning" @click="toRegister">注册</el-button>
    </div>
  </div>
</div>
</template>

<style scoped lang="less">
.admin {
  width: 100%;
  height: 100vh;
  display: flex;
  .login-box {
    margin: auto;
    width: 500px;
    height: 300px;
    border-radius: 10px;
    border: solid 1px var(--color-info);
    display: flex;
    flex-direction: column;
    h2 {
      margin: 0 auto;
    }
    .form {
      margin: auto;
      .el-button {
        width: 100%;
        margin: 10px auto;
      }
    }
  }
}
</style>